package com.study.spmongodb.wwj.juc.utils;

import java.util.Random;
import java.util.concurrent.Phaser;
import java.util.concurrent.TimeUnit;

/**
 * @author MI
 * @version 1.0
 * @date 2020/12/13 21:30
 */
public class PhaserExample3 {
    private final static Random random = new Random(System.currentTimeMillis());

    public static void main(String[] args) {
        final Phaser phaser = new Phaser(5);
        for (int i = 1; i < 5; i++) {
            final PhaserExample2.Athletes athletes = new PhaserExample2.Athletes(phaser, i);
            athletes.start();
        }
        new InjureAthletes(phaser, 5).start();
    }

    static class InjureAthletes extends Thread {
        private final Phaser phaser;
        private final int no;

        public InjureAthletes(Phaser phaser, int no) {
            this.phaser = phaser;
            this.no = no;
        }

        @Override
        public void run() {
            try {
                sport(" start running", " end running");
                sport(" start bicycle. ", " end bicycle. ");
                System.out.println(no + " i am injure");
                phaser.arriveAndAwaitAdvance();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        private void sport(String s, String s2) throws InterruptedException {
            System.out.println(no + s);
            TimeUnit.SECONDS.sleep(random.nextInt(5));
            System.out.println(no + s2);
            phaser.arriveAndAwaitAdvance();
        }
    }

    static class Athletes extends Thread {
        private final Phaser phaser;
        private final int no;

        public Athletes(Phaser phaser, int no) {
            this.phaser = phaser;
            this.no = no;
        }

        @Override
        public void run() {
            try {
                sport(" start running", " end running");
                sport(" start bicycle. ", " end bicycle. ");
                sport("  start long jump. ", "  end  long jump.");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        private void sport(String s, String s2) throws InterruptedException {
            System.out.println(no + s);
            TimeUnit.SECONDS.sleep(random.nextInt(5));
            System.out.println(no + s2);
            phaser.arriveAndAwaitAdvance();
        }
    }
}

